package com.xjj.gateway.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xjj.entity.ResponseEntity;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author : 王泰元
 * @date : 2022/10/21 14:22
 */
public class FilterUtils {
    private final static List<String> releasePath =
            new ArrayList<>(Arrays.asList("/captcha/check", "/captcha/get", "/login", "/logout","/sms"));

    /**
     * 判断请求路径是否需要拦截验证，如果包含上面集合中所定义的路径，则无需拦截
     *
     * @param uri 求路径
     * @return true : 需要拦截 ; false : 直接放行
     */
    public static boolean needFilter(String uri) {
        for (String path : releasePath) {
            if (uri.contains(path)) {
                return false;
            }
        }
        return true;
    }


    /**
     * 返回指定的想要实体类的 dataBuffer
     *
     * @param exchange       ServerWebExchange
     * @param responseEntity 统一响应
     * @return DataBuffer
     */
    public static Mono<Void> getResult(ServerWebExchange exchange, ResponseEntity<Object> responseEntity) {

        ServerHttpResponse response = exchange.getResponse();

        byte[] bytes = null;
        try {
            bytes = new ObjectMapper().writeValueAsString(responseEntity).getBytes(StandardCharsets.UTF_8);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        DataBuffer dataBuffer = response.bufferFactory().wrap(bytes);

        response.getHeaders().add("Content-Type", "application/json;charset=utf-8");

        return response.writeWith(Mono.just(dataBuffer));
    }
}
